<?php

namespace app\common\model;


use app\common\lib\ZhyxMongo;
use catchAdmin\permissions\model\Users;
use catcher\base\CatchModel;

class Contract extends BaseModel
{
    public function getLists($postData): array
    {
        //获取用户下级ID
        $userIds = $this->getUserIds();

        $match["deleted_at"] = 0;
        if (!empty($userIds)) {
            $match["contract_doctor.doctor_id"] = ['$in' => $userIds];
        }
        if (!empty($postData["name"])) {
            $match["name"] = ['$regex' => $postData["name"]];
        }
        if ($postData["status"] !== "") {
            $match["status"] = (int)$postData["status"];
        }
        if ($postData["groupId"] !== "") {
            //根据分组id获取成员id集合
            $patientIds = [];
            $groupInfo = (new CollectClass())->find($postData["groupId"]);
            if (!empty($groupInfo)) {
                //根据xpath获取所有的患者登记号
                $result = (new CollectClass())->where("xpath", "like", $groupInfo['xpath'])->select();
                if ($result !== null) {
                    foreach ($result as $k => $v) {
                        if (isset($v["patientList"]) && !empty($v["patientList"])) {
                            foreach ($v["patientList"] as $pk => $pv) {
                                $patientIds[] = $pv["patient_id"];
                            }
                        }
                    }
                }
            }
            if (!empty($patientIds)) {
                $match["his_id"] = ['$in' => $patientIds];
            } else {
                return [
                    "count" => 0,
                    "current" => $this->page,
                    "data" => [],
                    "limit" => $this->pageLimit
                ];
            }
        }
        $countPipeline = [['$match' => $match ?: (object)[]], ['$group' => ['_id' => '$patientId']], ['$count' => 'total_count']];
        //计算总条数
        $countResult = ZhyxMongo::getInstance()->setCollection("contract")->aggregate($countPipeline);
        $totalCount = 0;
        foreach ($countResult as $k => $v) {
            $totalCount = $v["total_count"];
        }
        $pipeline = [
            ['$match' => $match ?: (object)[]],
            ['$unwind' => ['path' => '$service_info.children', 'preserveNullAndEmptyArrays' => true]],
            [
                '$group' => ['_id' => '$patientId', 'his_id' => ['$first' => '$his_id'], 'patient_uuid' => ['$first' => '$patient_uuid'], 'status' => ['$last' => '$status'], 'contract_date' => ['$last' => '$contract_date'], 'id' => ['$last' => '$_id'], 'attention' => ['$last' => '$attention'], 'sex' => ['$first' => '$sex'], 'age' => ['$first' => '$inage'], 'service_info' => ['$push' => ['service_id' => '$service_info.children.id', 'service_name' => '$service_info.children.name', 'contract_id' => '$_id']]]
            ],
            [
                '$lookup' => ['from' => 'patient_info', 'localField' => 'his_id', 'foreignField' => 'patientId', 'as' => 'patientInfo']
            ],
            ['$project' => ['_id' => '$id', 'attention' => true, 'his_id' => true, 'name' => ['$first' => '$patientInfo.name'], 'birthdate' => ['$first' => '$patientInfo.birthdate'], 'contractTelphon' => ['$first' => '$patientInfo.presentTelphone'], 'status' => true, 'contract_date' => true, 'sex' => true, 'liveStatus' => ['$first' => '$patientInfo.liveStatus'], 'patient_uuid' => '$patient_uuid', 'age' => true, 'service_info' => true]],
            ['$skip' => (($this->page - 1) * $this->pageLimit)],
            ['$limit' => $this->pageLimit]
        ];
        $result = ZhyxMongo::getInstance()->setCollection("contract")->aggregate($pipeline);
        $arr = [];
        foreach ($result as $k => $v) {
            $v["_id"] = (string)$v["_id"];
            //$v["status_text"] = $this->getStatusText($v["status"]);
            $arr[] = $v;
        }
        return [
            "count" => $totalCount ?: 0,
            "current" => $this->page,
            "data" => $arr,
            "limit" => $this->pageLimit
        ];
    }

    public function getStatusTextAttr($value, $data): string
    {
        $statusArr = [1000 => "未开始", 1001 => "进行中", 1002 => "已终止", 1003 => "已结束"];
        return $statusArr[$data["status"]];
    }

    public function getServiceDayAttr($value, $data): string
    {
        if (isset($data["service_info"]["children"][0]["id"])) {
            $result = (new ServicePackage())->where("id", "=", $data["service_info"]["children"][0]["id"])->find();
            if (!empty($result)) {
                return $result["cycle"] ?? "";
            }
        }
        return "";
    }

    public function getContractDoctorAttr($value, $data)
    {
        foreach ($value as $k => &$v) {
            //根据医生id获取医生简介和头像
            $doctorInfo = (new Users())->getDoctorListByIds([$v["doctor_id"]]);
            $profession = [];
            if (isset($doctorInfo[0]["professionals"])) {
                $profession = array_column($doctorInfo[0]["professionals"], "name");
            }

            $v["good_at"] = $doctorInfo[0]["good_at"] ?? "";
            $v["introduction"] = $doctorInfo[0]["introduction"] ?? "";
            $v["department_name"] = $doctorInfo[0]["department_name"] ?? "";
            $v["job_name"] = $profession;
            $v["avatar"] = $doctorInfo[0]["avatar"] ?? "";

        }
        return $value;
    }

    public function getDoctorInfo(string $doctorId): array
    {
        $arr = [];
        $profession = [];
        $doctorInfo = (new Users())->getDoctorListByIds([$doctorId]);
        if (!empty($doctorInfo)) {
            if (isset($doctorInfo[0]["professionals"])) {
                $profession = array_column($doctorInfo[0]["professionals"], "name");
            }
            $arr["good_at"] = $doctorInfo[0]["good_at"] ?? "";
            $arr["introduction"] = $doctorInfo[0]["introduction"] ?? "";
            $arr["department_name"] = $doctorInfo[0]["department_name"] ?? "";
            $arr["job_name"] = $profession;
            $arr["avatar"] = $doctorInfo[0]["avatar"] ?? "";
        }
        return $arr;
    }


    /**
     * 医生获取签约
     */
    public function getDoctorContract($doctor_id)
    {
        $data['total'] = $this->where('contract_doctor.doctor_id', $doctor_id)->count();
        $data['today'] = $this->where('contract_date', date("Y-m-d"))->count();
        return $data;
    }


}